import {
	ACCESS_TOKEN,
	USER_ID,
	USER_INFO
} from '@/store/mutation-types'
import storage from '@/utils/storage'
import {
	loginIn,
	loginWechat
} from '@/api/login';
import {
	getInfo,
	logout
} from '@/api/user/index.js';
import {
	navTo,
	showToast
} from '@/core/app';
// 登录成功后执行
const loginSuccess = (commit, {
	token,
	id,
}) => {
	// 过期时间30天
	const expiryTime = 30 * 86400 * 3
	// 保存tokne和userId到缓存
	storage.set(USER_ID, id, expiryTime)
	storage.set(ACCESS_TOKEN, token, expiryTime)
	// 记录到store全局变量
	commit('SET_TOKEN', token)
	commit('SET_USER_ID', id)
	getInfo().then(res => {
		commit('SET_USER_INFO', res.data)
	})
}
const user = {
	state: {
		// 用户认证token
		token: uni.getStorageSync(ACCESS_TOKEN),
		// 用户ID
		userId: uni.getStorageSync(USER_ID),
		userInfo: uni.getStorageSync(USER_INFO),
		parent_id: null,
	},

	mutations: {
		SET_TOKEN: (state, value) => {
			state.token = value
			uni.setStorageSync(ACCESS_TOKEN, value)
		},
		SET_USER_ID: (state, value) => {
			state.userId = value
			uni.setStorageSync(USER_ID, value)
		},
		SET_USER_INFO: (state, value) => {
			state.userInfo = value
			uni.setStorageSync(USER_INFO, value)
		},
		M_PARENT_ID: (state, value) => {
			state.parent_id = value
		},
		SET_DYNAMIC_TABBAR(state, value) {
			state.dynamicTabbar = value;
		},
	},

	actions: {
		// 用户登录(普通登录: 输入手机号和验证码)
		async LoginWX({
			commit
		}, data) {
			const result = await loginWechat(data);
			if (result) {
				if (result.data.token) {
					loginSuccess(commit, {
						token: result.data.token,
						id: result.data.id,
					});
					return Promise.resolve(result);
				} else {
					return Promise.resolve(result);
				}
			}
		},

		// 用户登录(普通登录: 输入手机号和验证码)
		async LoginApp({
			commit
		}, data) {
			const result = await loginIn(data);
			if (result) {
				loginSuccess(commit, {
					token: result.data.token,
					id: result.data.id
				});
				return Promise.resolve(result);
			} else {
				return Promise.resolve(result);
			}
		},
		// H5登录
		async LoginH5({
			commit
		}, data) {
			const result = await loginIn(data);
			if (result) {
				if (result.data.token) {
					loginSuccess(commit, {
						token: result.data.token,
						id: result.data.id
					});
					return Promise.resolve(result);
				} else {
					return Promise.resolve(result);
				}
			}
		},
		// 退出登录
		Logout({
			commit
		}, data) {
			const store = this;
			if (store.getters.userId > 0) {
				// logout().then(res => {
				// if (res) {
				storage.remove(USER_ID)
				storage.remove(ACCESS_TOKEN)
				storage.remove(USER_INFO)
				// 记录到store全局变量
				commit('SET_TOKEN', '')
				commit('SET_USER_ID', null)
				commit('SET_USER_INFO', null)
				uni.removeStorageSync('userInfo-xunche')
				return Promise.resolve({
					result: true
				});
				// }
				// })
			}
		},
	}
}

export default user